package com.yjt.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author 曾智平
 * @Description: 网关拦截
 * @date 2021/5/2516:47
 */
@Slf4j
@Component
public class NormalGatewayFilter implements GlobalFilter {
    /**
     * 需要放行的路径
     * 登录请求
     * 接口文档路径
     */
    private final static String[] PASS_PATH = {"/oauth/token","/v2/api-docs"};
    /**
     * token请求头名称
     */
    private static final String  AUTHORIZATION = "Authorization";
    /**
     * token前缀
     */
    private static final String  BEARER = "Bearer ";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        for (String passPath:PASS_PATH) {
            if (path.contains(passPath)) {
                return chain.filter(exchange);
            }
        }
//        //其他，验证token
//        String token = exchange.getRequest().getHeaders().getFirst(AUTHORIZATION);
//        token = token == null ? "" : token.replace(BEARER, "");
//        // 如果请求头不存在 Token
//        if (StringUtils.isBlank(token)) {
//            return this.getResponseError(exchange, "请先登录");
//        }
        return chain.filter(exchange);
    }


    /**
     * 返回错误信息
     *
     * @param exchange
     * @param msg
     * @return
     */
    private Mono<Void> getResponseError(ServerWebExchange exchange, String msg) {
        ServerHttpResponse response = exchange.getResponse();
        JSONObject message = new JSONObject();
        message.put("code", -1);
        message.put("message", msg);
        byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }


}
